package com.breeze.media.audio;


import android.content.Intent;
import android.media.AudioAttributes;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTrack;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import androidx.appcompat.app.AppCompatActivity;

import com.breeze.media.R;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;

public class AudioActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";

    InputStream mInputStream;
    private int minBufferSize;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_audio);
        InputStream inputStream = getResources().openRawResource(R.raw.ring);
        mInputStream = new BufferedInputStream(inputStream);
        minBufferSize = AudioTrack.getMinBufferSize(SAMPLE_RATE_HZ, AudioFormat.CHANNEL_OUT_STEREO, AudioFormat.ENCODING_PCM_16BIT);
    }

    private static final int SAMPLE_RATE_HZ = 44100;

    public void play(View view) {
        AudioAttributes attributes = new AudioAttributes.Builder()
                .setUsage(AudioAttributes.USAGE_MEDIA)
                .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
                .build();
        AudioFormat format = new AudioFormat.Builder()
                .setChannelMask(AudioFormat.CHANNEL_OUT_STEREO)
                .setSampleRate(SAMPLE_RATE_HZ)
                .setEncoding(AudioFormat.ENCODING_PCM_16BIT)
                .build();
        AudioTrack audioTrack = new AudioTrack(attributes, format, minBufferSize, AudioTrack.MODE_STREAM, AudioManager.AUDIO_SESSION_ID_GENERATE);
        audioTrack.play();

        byte[] data = new byte[1024];
        while (audioTrack.getPlayState() == AudioTrack.PLAYSTATE_PLAYING) {
            try {
                int readSize = mInputStream.read(data);
                Log.i(TAG, "play: readSize=" + readSize);
                if (readSize > 0) {
                    audioTrack.write(data, 0, readSize);
                } else {
                    audioTrack.stop();
                    audioTrack.release();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void start(Class<?> cls) {
        startActivity(new Intent(this, cls));
    }

    public void openRecord(View view) {
        start(AudioRecordActivity.class);
    }
}